package com.newlink.building.utils

import android.content.Context
import android.os.Environment
import android.widget.Toast
import com.newlink.building.NL_App
import com.newlink.building.R
import com.newlink.building.utils.http.Module_Phone_HttpEntity
import java.io.File
import java.io.IOException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.asRequestBody
import org.linphone.core.tools.Log

/**
 * Created by xiaodong on 2022/11/30.
 */
object Module_Phone_DeviceUtils {

    fun getAppVersion(context: Context): Int {

        var version = -1
        try {
            val manager = context.packageManager
            val packageInfo = manager.getPackageInfo(context.packageName, 0)
            version = packageInfo.versionCode
            return version
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return version
    }

    fun getVersionName(context: Context): String {

        var version = ""
        try {
            val manager = context.packageManager
            val packageInfo = manager.getPackageInfo(context.packageName, 0)
            version = packageInfo.versionName
            return version
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return version
    }


    fun checkNewVersion(checkResult: (code: Int, msg: String) -> Unit) {

        Module_Phone_HttpEntity(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                checkResult(500, e.toString())
            }

            override fun onResponse(call: Call, response: Response) {
                val responseData = response.body?.string()
                responseData?.let {
                    checkResult(200, it)
                }
            }
        }).apply {
            request()
        }
    }

    private fun asyncUploadFile() {
        val url = ""
        // 创建file
        val filePath = Environment.getExternalStorageDirectory().absolutePath
        val file = File(filePath, "test.txt")

        // 创建request请求对象
        val request = Request.Builder()
            .url(url)
            .post(file.asRequestBody("text/txt; charset=utf-8".toMediaType()))
            .build()

        // 创建call并调用enqueue()方法实现网络请求
        OkHttpClient().newCall(request)
            .enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                }

                override fun onResponse(call: Call, response: Response) {
                }
            })
    }

    fun excuteOpenDoorCommand(url: String) {
        Log.e("yxd excuteOpenDoorCommand  $url")
        if (!url.contains("http://") && !url.contains("https://")) {
            Toast.makeText(NL_App.context, "HTTP Command 格式不正确！", Toast.LENGTH_LONG)
                .show()
            return
        }
        GlobalScope.launch(Dispatchers.IO) {
            val request = Request.Builder().url(url).build()
            val client = OkHttpClient.Builder().authenticator(object : Authenticator {
                override fun authenticate(route: Route?, response: Response): Request? {
                    val credential = Credentials.basic("admin", "admin")
                    return response.request.newBuilder().header("Authorization", credential).build()
                }
            }).build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    GlobalScope.launch(Dispatchers.Main) {
                        Toast.makeText(
                            NL_App.context,
                            NL_App.coreContext.context.getString(R.string.call_error_io_error),
                            Toast.LENGTH_LONG
                        ).show()
                    }
                    Log.e("yxd onFailure $e")
                }

                override fun onResponse(call: Call, response: Response) {
                    val data = response.body?.string()
                    Log.e("yxd onResponse $data")
                    if (!data.isNullOrEmpty()) {
                        GlobalScope.launch(Dispatchers.Main) {
                            if (!data.isNullOrEmpty()) {
                                when {
                                    data.contains("success") -> {
                                        Toast.makeText(
                                            NL_App.context,
                                            NL_App.context.getString(R.string.opendoor_success),
                                            Toast.LENGTH_LONG
                                        ).show()
                                    }

                                    data.contains("fail") -> {
                                        Toast.makeText(
                                            NL_App.context,
                                            NL_App.context.getString(R.string.opendoor_failure),
                                            Toast.LENGTH_LONG
                                        ).show()
                                    }
//                                    else -> {
//                                        Toast.makeText(FvlApplication.context, "已执行开门操作！", Toast.LENGTH_LONG).show()
//                                    }
                                }
                            }
                        }
                    }
                }
            })
        }
    }
}
